﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;


namespace SymbolicLinkManageCore.Library
{
    public class ArraysRead<T>:IEnumerable<T>
    {
        private T[][] Source;
        private int[] ints;
        public ArraysRead(T[][] Arrays) 
        {
            Source = Arrays;
            m_count = Source.Sum(p => p.Length);
            ints = new int[Source.Length];
            ints[0] = Arrays[0].Length;
            for (int i = 1; i < Arrays.Length; i++)
                ints[i] = Arrays[i].Length + ints[i - 1];
        }
        public bool IsReadOnly { get; } = true;
        
        public T this[int index]
        {
            get
            {
                int j = 0;
                for (int i = 0; i < ints.Length; i++)
                {
                    if (index < ints[i])
                    {
                        j = i;
                        break;
                    }
                }
                if (j < 1)
                    return Source[0][index];

                index -= ints[j - 1];

                return Source[j][index]!;
            }

        }

        private int m_count;
        public int Count => m_count;
        public IEnumerator<T> GetEnumerator()
        {
            foreach (T[] item in Source)
            {
                foreach (T _item in item)
                    yield return _item;
            }
        }
        IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();

        public int IndexOf(T item)
        {
            T[] _values;
            int index = 0;
            for (int i = 0; i < Source.Length; i++)
            {
                _values= Source[i];
                if (_values == null || _values.Length < 1)
                    continue;
                for (int j = 0; j < _values.Length; j++)
                {
                    if (_values[j]?.Equals(item) ?? false)
                        return index;
                    index++;
                }
            }
            return -1;
        }
        
        public bool Contains(T item)
        {
            foreach (T[] _item in Source)
            {
                if(_item.Contains(item))
                    return true;
            }
            return false;
        }

        
    }
}
